package com.jj.lib;

import android.content.Context;
import android.util.Log;

import com.jj.base.BaseApplication;
import com.jj.network.okhttp.BaseCallback;
import com.jj.network.okhttp.NetCacheInterceptor;
import com.jj.network.okhttp.HttpLoggingInterceptor;
import com.jj.network.okhttp.NoNetCacheInterceptor;
import com.jj.network.okhttp.ProgressListener;
import com.jj.network.okhttp.ProgressResponseBody;
import com.jj.network.okhttp.StringCall;
import com.jj.util.JJUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by qmsoft05 on 2017/3/16.
 */

public enum OkHttpUtils {
    API;
    private static final String APP_URL = "http://api.jisuapi.com/driverexam/query";
    public static final long DEFAULT_READ_TIMEOUT_MILLIS = 15 * 1000;
    public static final long DEFAULT_WRITE_TIMEOUT_MILLIS = 20 * 1000;
    public static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = 20 * 1000;
    private static final long HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;
    private final OkHttpClient mOkHttpClient;

    OkHttpUtils() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        //包含header、body数据
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
        okBuilder.readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        okBuilder.writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        okBuilder.connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        if (BuildConfig.LOG_DEBUG) {
            okBuilder.addInterceptor(loggingInterceptor); //http数据log，日志中打印出HTTP请求&响应数据
        }
        /**设置缓存路径和缓存大小，生效需要服务器设置Cache-Control或者客户端重写的Response的Cache-Control，addNetworkInterceptor*/
        okBuilder.cache(new Cache(new File(BaseApplication.application().getCacheDir(), "OKHttpCache"), HTTP_RESPONSE_DISK_CACHE_MAX_SIZE));
        okBuilder.addInterceptor(new NoNetCacheInterceptor());
        okBuilder.addNetworkInterceptor(new NetCacheInterceptor()); //可设置缓存时间
        mOkHttpClient = okBuilder.build();

    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public void setCache(Context appContext) {
        final File baseDir = appContext.getApplicationContext().getCacheDir();
        if (baseDir != null) {
            final File cacheDir = new File(baseDir, "HttpResponseCache");
            mOkHttpClient.newBuilder().cache((new Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE))).build();
        }
    }

    /**
     * 拼接URL
     */
    public String jointURL(String url, Map<String, String> values) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(url).append("?");
        Set<String> keys = values.keySet();
        for (String key : keys) {
            buffer.append(key).append("=").append(values.get(key)).append("&");
        }
        return buffer.toString().substring(0, buffer.toString().length() - 1);
    }

    private static final CacheControl CAACHE_CONT = new CacheControl.Builder().onlyIfCached().build();

    public void getDriverexam(int pagesize, int pagenum, StringCall hcall) {
        Map<String, String> params = new HashMap<>();
        params.put("appkey", "95e6047cce6f24ed");
        params.put("type", "C1");
        params.put("subject", "1");
        params.put("pagesize", pagesize+""); //每页数量 默认1
        params.put("pagenum", pagenum+""); // 当前页数
        params.put("sort", "normal");
        Request request = new Request.Builder().url(jointURL(APP_URL, params)).build();
        if (JJUtils.getNetworkType(BaseApplication.application()) == 0)
            request = new Request.Builder().cacheControl(CAACHE_CONT).url(jointURL(APP_URL, params)).build();
        mOkHttpClient.newCall(request).enqueue(hcall);
    }
    public void getDriverexam(int pagesize, int pagenum, BaseCallback hcall) {
        Map<String, String> params = new HashMap<>();
        params.put("appkey", "95e6047cce6f24ed");
        params.put("type", "C1");
        params.put("subject", "1");
        params.put("pagesize", pagesize+""); //每页数量 默认1
        params.put("pagenum", pagenum+""); // 当前页数
        params.put("sort", "normal");
        Request request = new Request.Builder().url(jointURL(APP_URL, params)).build();
        if (JJUtils.getNetworkType(BaseApplication.application()) == 0)
            request = new Request.Builder().cacheControl(CAACHE_CONT).url(jointURL(APP_URL, params)).build();
        mOkHttpClient.newCall(request).enqueue(hcall);
    }

    /**
     * post请求
     * @param action
     * @param hcall
     */
    public void postAPIs(String action, BaseCallback hcall) {

        FormBody.Builder form = new FormBody.Builder();
//        form.add("key", action);
        final ProgressListener progressListener = new ProgressListener() {
            @Override
            public void onProgress(long currentLength, long contentLength, boolean done) {
                Log.e("dd", "===="+currentLength +"**"+contentLength);
            }
        };

        Request request = new Request.Builder().url("http://121.15.220.153/imtt.dd.qq.com/16891/433949400FC6E29FDE9E209099BFE5BC.apk?mkey=58fb0600d9410fce&f=9432&c=0&fsname=com.tencent.mobileqq_6.7.1_500.apk&csr=1bbd&p=.apk").post(form.build()).build();
        new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder().body(
                        new ProgressResponseBody(originalResponse.body(), progressListener))
                        .build();

            }
        }).build().newCall(request).enqueue(hcall);
    }

    /**
     * get请求
     */
    public void getAPI(int pagesize, int pagenum, StringCall hcall) {
        Map<String, String> params = new HashMap<>();
        params.put("appkey", "95e6047cce6f24ed");
        params.put("type", "C1");
        params.put("subject", "1");
        params.put("pagesize", pagesize+""); //每页数量 默认1
        params.put("pagenum", pagenum+""); // 当前页数
        params.put("sort", "normal");
        Request request = new Request.Builder().url(jointURL(APP_URL, params)).build();
        mOkHttpClient.newCall(request).enqueue(hcall);
    }

    /**
     * post请求
     * @param action
     * @param hcall
     */
    public void postAPI(String action, StringCall hcall) {

        FormBody.Builder form = new FormBody.Builder();
        form.add("key", action);
        Request request = new Request.Builder().url("http://xx.com").post(form.build()).build();
        mOkHttpClient.newCall(request).enqueue(hcall);
    }


    /**
     * 取消所有请求
     */
    public void cancelAll() {
        mOkHttpClient.dispatcher().cancelAll();
    }

}
